/*
 * MainActivity serves as the hub for users to manage buildings & inventory. From this page, the user will
 * be directed to various sub activities to complete operations such as creating, updating, & deleting buildings 
 * & inventory, & managing the application.
 */
package com.example.wmuqrreader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


@SuppressLint("WorldReadableFiles")
public class MainActivity extends Activity {
	
	DatabaseHandler db;
	
	ListView list;
	
	Button button_new;
	Button button_scan;
	
    String app_version 		= "1.0.0";
    String app_contact 		="Ryan McGregor";
    String app_email 		="ryan.mcgregor@wmich.edu";
    String app_phone 		="(269) 387.5420";
    String app_dev1			="Joe Meyer";
    String app_dev1_email 	="joseph.w.meyer@live.com";
    String app_dev2			= "";
    String app_dev2_email	= "";
	
	// OnCreate is auto-generated & is always the first method to be called by a new activity
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        setContentView(R.layout.activity_main);		//Link this activity to a specific view
        
        /*After this...lets do work*/
        
        button_new 		= (Button) findViewById(R.id.btn_new);   
		button_scan 	= (Button) findViewById(R.id.btn_scan);
		
		db 				= new DatabaseHandler(this);
		list 			= (ListView) findViewById(R.id.listView1);
		
        List<Building> building = new ArrayList<Building>();
        building = db.getAllBuilding();
        db.close();            
        
        CustomBuildingListViewAdapter adapter = new CustomBuildingListViewAdapter(this, R.layout.simple_list_building, building);
        
        //Add a function for the EDIT row click - takes user to inventory list
        list.setAdapter(adapter);       
        list.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
            	
            	Intent intent = new Intent();            	
            	
            	if(v != null)
            	{
	            	intent.putExtra("BUILDING", (String) ((TextView) v.findViewById(R.id.textView_bldgId)).getText());
	            	intent.putExtra("NAME", (String) ((TextView) v.findViewById(R.id.textView_building)).getText());
	            	
	            	intent.setClass(MainActivity.this, InvActivity.class);				
			        startActivityForResult(intent, 0);
            	}
            	else
            	{
            		Toast.makeText(getApplicationContext(), "ALERT: building not found. Contact the WMU DPS IT office for assistance", Toast.LENGTH_LONG).show();            		           		
            	}            	
            }
        });
           
        //Add a function for the EDIT long click - takes user to building edit screen
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
        {

			@Override
			public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
            	Intent intent = new Intent();
            	
            	if(v != null)
            	{
	            	intent.putExtra("BUILDING", (String) ((TextView) v.findViewById(R.id.textView_bldgId)).getText());
	            	
	            	intent.setClass(MainActivity.this, BuildingActivity.class);				
			        startActivityForResult(intent, 0);
			        return true;
            	}
            	else
            	{
            		Toast.makeText(getApplicationContext(), "ALERT: building not found. Contact the WMU DPS IT office for assistance", Toast.LENGTH_LONG).show();            		           		
            	}
				return false;
			}
        });        
        
        //Add a function for the NEW button click          
        button_new.setOnClickListener(new View.OnClickListener()
        {	
			@Override
			public void onClick(View v) {
				
				//Lets make a new intent (it is completely blank right now)
				Intent intent = new Intent();
				
				intent.setClass(MainActivity.this, BuildingActivity.class);			
		        startActivityForResult(intent, 0);	        
			}
		});
        
        //Add a function for the SCAN button click
        button_scan.setOnClickListener(new View.OnClickListener()
        {
                        
                @Override
                public void onClick(View v) {
                        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                        intent.setPackage("com.google.zxing.client.android");
                        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                        startActivityForResult(intent, 1);                     
                }
         });         
    }  

    // onActivityResult is a callback function that only occurs once a process returns to the activity that called it.
    public void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        if (requestCode == 0) 
        {
        	if (resultCode == RESULT_OK) 
            {
        		//Refresh the Inventory List activity to display the updated data     		
        		Intent refresh = new Intent();        		
        		refresh.setClass(this, MainActivity.class);
        		
        		//refresh.putExtra("BUILDING", building_id);
        		
        		startActivity(refresh);
        		this.finish();
            }
        }
        
        if (requestCode == 1 ) 
        {
            if (resultCode == RESULT_OK) 
            {
            	Intent gotInventory = new Intent();   
                String contents = intent.getStringExtra("SCAN_RESULT");   
                
                Inventory inventory_scan = db.getInventory( Integer.parseInt(contents), "QR" ); 
                if(inventory_scan.get_inv() == -1)
                {
                	Toast.makeText(getApplicationContext(), "Creating New...", Toast.LENGTH_LONG).show();
                }
                else
                {
                	 Toast.makeText(getApplicationContext(), "Got: " + contents, Toast.LENGTH_LONG).show();
                	 int id = inventory_scan.get_id();
                	 gotInventory.putExtra("ID", Integer.toString(inventory_scan.get_id()));  
                	 gotInventory.putExtra("BUILDING", Integer.toString(inventory_scan.get_building()));  
                }
                
	           	gotInventory.setClass(MainActivity.this, TallActivity.class);
	            startActivity(gotInventory);
            } 
            else if (resultCode == RESULT_CANCELED) 
            {
                // Handle cancel
            }
        }
    }

    // Auto-generated method to create menu options
	@Override
    public boolean onCreateOptionsMenu(Menu menu)
	{
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);        
       
        menu.add("Export Data").setOnMenuItemClickListener(new OnMenuItemClickListener()
        {
			public boolean onMenuItemClick(MenuItem clickedItem)
            {
				SimpleDateFormat	sdf = new SimpleDateFormat("yyyy-MM-dd");
				
				ShowProgress();  
            	BuildExport(sdf);   
            	SendEmail("WMU Fire Export " + sdf.format(new Date()) + ".csv");
            	
                return true;
            }
        });
        
        menu.add("Import Data").setOnMenuItemClickListener(new OnMenuItemClickListener()
        {
            public boolean onMenuItemClick(MenuItem clickedItem)
            {
            	Toast.makeText(getApplicationContext(), "Please standby while the import is processed.", Toast.LENGTH_LONG).show();
                try 
                {        
                	//TODO: Let's make this a method...
                	//{
                	File pa = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/db_building.csv");
                    BufferedReader br = new BufferedReader(new FileReader(pa));
                    String line;
                    
                    while ((line = br.readLine()) != null) 
                    {
                    	Building building;
                    	String[] row = line.split(",");
                    	
                    	//TODO: check ID. If match, update, else add
                    	building = new Building(row[1], row[2].toUpperCase());
                    	
                    	db.addBuilding(building);                
                    }
                    //}
                    
                }
                catch (IOException e) 
                {
                	ShowError();
                	return false;
                }
                Toast.makeText(getApplicationContext(), "Import complete!", Toast.LENGTH_LONG).show();
                
                Refresh();    
                
                return true;
            }
            
        });
        
        menu.add("Settings").setOnMenuItemClickListener(new OnMenuItemClickListener()
        {
            public boolean onMenuItemClick(MenuItem clickedItem)
            {
            	//TODO: Show settings menu
            	//	http://developer.android.com/design/patterns/settings.html
            	ShowSettings();
            	return true;
            }
            
        });
        
        menu.add("Help").setOnMenuItemClickListener(new OnMenuItemClickListener()
        {
            public boolean onMenuItemClick(MenuItem clickedItem)
            {
            	ShowHelp();
            	return true;
            }
            
        });
        
        return true;
    }
	
	//Create the export file
	private void BuildExport(SimpleDateFormat date)
	{
		String 				string = "";
    	
    	List<Building> 		bldg = db.getAllBuilding();
    	List<Inventory> 	inv = db.getAllInventory(Integer.MIN_VALUE);
    	List<Inspection> 	ins = db.getAllInspection(Integer.MIN_VALUE);            	
    	
    	String filename = "wmu_fire_export_" + date.format(new Date()) + ".csv";

    	
    	FileOutputStream outputStream;

    	try 
    	{
    		//This is usually bad practice, but we need to send this file externally
    		outputStream = openFileOutput(filename, Context.MODE_WORLD_READABLE);
    	  
    		outputStream.write("BUILDING,\n".getBytes());
    		Log.d("BUIDLING", "WRITE");            	 
    		//Write the building list
    		for(Building b : bldg)
    		{            		  
    			string = b.get_id() + "," + b.get_num() + "," + b.get_building() + ",\n";
    			outputStream.write(string.getBytes());
    			Log.d("WRITE: ", string);
    		}
    	  
    		Toast.makeText(getApplicationContext(), "Building export complete!", Toast.LENGTH_LONG).show();
    	  
    		outputStream.write("INVENTORY,\n".getBytes());
    		Log.d("Inventory", "WRITE");
    		//Write the inventory list
    		for(Inventory i : inv)
    		{
    			string = i.get_id() + ","			
    				  + i.get_location() + ","
    				  + i.get_serialNum() + ","
    				  + i.get_type() + ","
    				  + i.get_brand() + ","
    				  + i.get_svDate()	+ ","	
    				  + i.get_year() + ","
    				  + i.get_inv() + ","
    				  + i.get_qr() + ","
    				  + i.get_building() + ",\n";
    			outputStream.write(string.getBytes());
    			Log.d("WRITE: ", string);
    		}
    	  
    		Toast.makeText(getApplicationContext(), "Inventory export complete!", Toast.LENGTH_LONG).show();
    	  
    		outputStream.write("INSPECTION,\n".getBytes());
    		Log.d("Inspection", "WRITE");
    		//Write the Inspection list
    		for(Inspection s : ins)
    		{
    			string = s.get_id() + ","
    				  + s.get_qr() + ","
    				  + s.get_svDate() + ","
    				  + s.is_foundOk() + ","
    				  + s.is_cleaned() + ","
    				  + s.is_replacedTie() + ","
    				  + s.is_recharged() + ","
    				  + s.is_newMount() + ","
    				  + s.get_otherNotes()+ ","
    				  + s.get_officerName() + ","
    				  + ",\n";
    			outputStream.write(string.getBytes()); 
    			Log.d("WRITE: ", string);
    		}
	
    		outputStream.close();
    		Toast.makeText(getApplicationContext(), "Database export complete!", Toast.LENGTH_LONG).show();
      	} 
      	catch (Exception e) 
      	{
      		e.printStackTrace();
      	}
	}
	
	//Make sure the main page shows the most data
	private void Refresh()
	{
		//Refresh the Inventory List activity to display the updated data     		
		Intent refresh = new Intent();        		
		refresh.setClass(this, MainActivity.class);
		
		startActivity(refresh);
	}
	
	// Show user something meaningful when import goes awry
	private void ShowError()
	{
		new AlertDialog.Builder(this)
		.setIcon(android.R.drawable.ic_dialog_info)
        .setTitle("Export Data File")
        .setMessage("Please ensure all three files: db_building.csv, db_inventory.csv, db_inspection.csv are all saved to " 
        		+ "the Download folder of your android device & are properly formatted. \nPlease contact WMU DPS IT support with questions")
        .setNegativeButton("Ok", null)
	    .show();
	}
	
	// Show user something meaningful while data is being exported
	private void ShowProgress()
	{
		new AlertDialog.Builder(this)
		.setIcon(android.R.drawable.ic_dialog_info)
        .setTitle("Export Data File")
        .setMessage("Please wait while the data file is generated. You will be prompted once the process is complete. "
        		+ "The application may be unresponsive in the meantime")
        //TODO: Holy cow, this would be a GREAT place to thread operations. The above message is never a sign of good programming
       	//TODO: Add progress bar to show how far along the operation is
        .setNegativeButton("Ok", null)
	    .show();
	}
	
	//Function that prepares the email for sending
	private void SendEmail(String filename)
	{
		  Intent intent = new Intent(Intent.ACTION_SEND);
	
	  	  intent.setType("application/txt");
	
	  	  intent.putExtra(Intent.EXTRA_SUBJECT, filename);
	  	  intent.putExtra(Intent.EXTRA_TEXT, "Please separate each table into it's own file before "
	  	  		+ "attempting to import into an SQL database.");
	  	  

	  	  File[] f = getApplicationContext().getFilesDir().listFiles();
	  	  
	  	  //Here, we attach the file. We use values to grab the most recent
	  	  Uri uri = Uri.parse("file:" + f[f.length-1]);
	  	  intent.putExtra(android.content.Intent.EXTRA_STREAM, uri);
	
	  	  try 
	  	  {
	  		  startActivity(Intent.createChooser(intent, "Choose an Email Client"));
	  	  }
	  	  catch (android.content.ActivityNotFoundException ex) 
	  	  {
	  		  Toast.makeText(getApplicationContext(), "Please install an Email Client", Toast.LENGTH_SHORT).show();
	  	  }
	}
	
	//Temporary! This shows the user a dialog box until a settings menu is implemented. This function should be removed after the fact
	private void ShowSettings()
	{
		new AlertDialog.Builder(this)
		.setIcon(android.R.drawable.ic_dialog_info)
        .setTitle("WMU QR Reader v" + app_version)
        .setMessage("No settings are available at this time.")
        .setNegativeButton("Ok", null)
	    .show();
	}
	
	//This method shows the user information on how to get help for the application
	private void ShowHelp()
	{
		new AlertDialog.Builder(this)
		.setIcon(android.R.drawable.ic_dialog_info)
		.setTitle("WMU QR Reader v"  + app_version)
        .setMessage("For assistance, user guides, or issue reporting, please contact WMU DPS tech support. "
        		+ "\n\t" + app_contact
        		+ "\n\t" + app_phone
        		+ "\n\t" + app_email
        		+ "\n\n\tDeveloper: " + app_dev1)
        .setNegativeButton("Ok", null)
	    .show();
	}
    
}
